package com.eb.controller;

import com.eb.pojo.Goods;
import com.eb.pojo.Result;
import com.eb.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import util.PageUtil;
import util.ReducePriceUtils;

import javax.persistence.Table;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("goods")
@CrossOrigin
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ReducePriceUtils reducePriceUtils;

    @GetMapping
    public PageUtil<Map<String,Object>> mohu(@RequestParam(value ="goodsName",defaultValue = "",required = false)String goodsName,
                                             @RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
                                             @RequestParam(value = "size",defaultValue = "10",required = false)Integer size){

            Page<Map<String,Object>> mohu=goodsService.mohu(goodsName,page,size);
            return new PageUtil<Map<String,Object>>(page,mohu.getTotalElements(),mohu.getContent(),size);
    }
    @PostMapping
    public Result addGoods(@RequestBody Goods goods){
        try {
            goodsService.addGoods(goods);
            return new Result(true,"添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"添加失败");
        }
    }
    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id")int id){
        try {
            goodsService.del(id);
            return new Result(true,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,"删除失败");
        }
    }
    @PutMapping
    public Result updateGoods(@RequestBody Goods goods){
        try {
            goodsService.updateGoods(goods);
            return new Result(true,"修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改失败");
        }
    }
    @GetMapping("/id/{id}")
    public Goods findBygoods(@PathVariable("id")int id){
        return  goodsService.findBygoods(id);
    }
    @GetMapping("/list")
    public List<Goods> list(){
        return goodsService.list();
    }

}
